<template>
  <t-dialog header="Cron表达式生成器" :visible.sync="visible"
            :onClose="closeDialog"
            :closeOnOverlayClick="false"
            width="50%"
            top="5%"
            @confirm="onSubmit"

  >
    <div style="height: 65vh">
      <t-tabs theme="card" v-model="tabValue">
        <t-tab-panel label="秒" value="1" v-if="shouldHide('second')">
          <crontab-second
            @update="updateCrontabValue"
            :check="checkNumber"
            :cron="crontabValueObj"
            ref="cronsecond"
          />
        </t-tab-panel>

        <t-tab-panel label="分钟" value="2" v-if="shouldHide('min')">
          <crontab-min
            @update="updateCrontabValue"
            :check="checkNumber"
            :cron="crontabValueObj"
            ref="cronmin"
          />
        </t-tab-panel>

        <t-tab-panel label="小时" value="3" v-if="shouldHide('hour')">
          <crontab-hour
            @update="updateCrontabValue"
            :check="checkNumber"
            :cron="crontabValueObj"
            ref="cronhour"
          />
        </t-tab-panel>

        <t-tab-panel label="日" value="4" v-if="shouldHide('day')">
          <crontab-day
            @update="updateCrontabValue"
            :check="checkNumber"
            :cron="crontabValueObj"
            ref="cronday"
          />
        </t-tab-panel>

        <t-tab-panel label="月" value="5" v-if="shouldHide('month')">
          <crontab-month
            @update="updateCrontabValue"
            :check="checkNumber"
            :cron="crontabValueObj"
            ref="cronmonth"
          />
        </t-tab-panel>

        <t-tab-panel label="周" value="6" v-if="shouldHide('week')">
          <crontab-week
            @update="updateCrontabValue"
            :check="checkNumber"
            :cron="crontabValueObj"
            ref="cronweek"
          />
        </t-tab-panel>

        <t-tab-panel label="年" value="7" v-if="shouldHide('year')">
          <crontab-year
            @update="updateCrontabValue"
            :check="checkNumber"
            :cron="crontabValueObj"
            ref="cronyear"
          />
        </t-tab-panel>
      </t-tabs>

      <div class="popup-main">
        <div class="popup-result">
          <p class="title">时间表达式</p>
          <table>
            <thead>
            <th v-for="item of tabTitles" width="40" :key="item">{{item}}</th>
            <th>Cron 表达式</th>
            </thead>
            <tbody>
            <td>
              <span>{{crontabValueObj.second}}</span>
            </td>
            <td>
              <span>{{crontabValueObj.min}}</span>
            </td>
            <td>
              <span>{{crontabValueObj.hour}}</span>
            </td>
            <td>
              <span>{{crontabValueObj.day}}</span>
            </td>
            <td>
              <span>{{crontabValueObj.month}}</span>
            </td>
            <td>
              <span>{{crontabValueObj.week}}</span>
            </td>
            <td>
              <span>{{crontabValueObj.year}}</span>
            </td>
            <td>
              <span>{{crontabValueString}}</span>
            </td>
            </tbody>
          </table>
        </div>
        <crontab-result :ex="crontabValueString"></crontab-result>
      </div>
    </div>
    <template #footer>
      <t-button theme="primary" @click="submitFill">确定</t-button>
      <t-button theme="default" variant="outline" @click="clearCron">重置</t-button>
      <t-button theme="default" @click="closeDialog">取消</t-button>
    </template>
  </t-dialog>
</template>

<script>
import CrontabSecond from "./second.vue";
import CrontabMin from "./min.vue";
import CrontabHour from "./hour.vue";
import CrontabDay from "./day.vue";
import CrontabMonth from "./month.vue";
import CrontabWeek from "./week.vue";
import CrontabYear from "./year.vue";
import CrontabResult from "./result.vue";

export default {
  name: "vcrontab",
  components: {
    CrontabSecond,
    CrontabMin,
    CrontabHour,
    CrontabDay,
    CrontabMonth,
    CrontabWeek,
    CrontabYear,
    CrontabResult,
  },
  props: ["expression", "hideComponent"],
  data() {
    return {
      tabValue: "1",
      visible: true,
      loading: false,
      tabTitles: ["秒", "分钟", "小时", "日", "月", "周", "年"],
      tabActive: 0,
      myindex: 0,
      crontabValueObj: {
        second: "*",
        min: "*",
        hour: "*",
        day: "*",
        month: "*",
        week: "?",
        year: "",
      },
    };
  },
  computed: {
    crontabValueString() {
      const obj = this.crontabValueObj;
      return `${obj.second
      } ${
        obj.min
      } ${
        obj.hour
      } ${
        obj.day
      } ${
        obj.month
      } ${
        obj.week
      }${obj.year === "" ? "" : ` ${obj.year}`}`;
    },
  },
  watch: {
    expression: "resolveExp",
    hideComponent(value) {
      // 隐藏部分组件
    },
  },
  mounted() {
    this.resolveExp();
  },
  methods: {
    shouldHide(key) {
      return !(this.hideComponent && this.hideComponent.includes(key));
    },
    resolveExp() {
      // 反解析 表达式
      if (this.expression) {
        const arr = this.expression.split(" ");
        if (arr.length >= 6) {
          // 6 位以上是合法表达式
          const obj = {
            second: arr[0],
            min: arr[1],
            hour: arr[2],
            day: arr[3],
            month: arr[4],
            week: arr[5],
            year: arr[6] ? arr[6] : "",
          };
          this.crontabValueObj = {
            ...obj,
          };
          Object.keys(obj).forEach(i=>{
            if (obj[i]) this.changeRadio(i, obj[i]);
          })
        }
      } else {
        // 没有传入的表达式 则还原
        this.clearCron();
      }
    },
    // tab切换值
    tabCheck(index) {
      this.tabActive = index;
    },
    // 由子组件触发，更改表达式组成的字段值
    updateCrontabValue(name, value, from) {
      this.crontabValueObj[name] = value;
      if (from && from !== name) {
        console.log(`来自组件 ${from} 改变了 ${name} ${value}`);
        this.changeRadio(name, value);
      }
    },
    // 赋值到组件
    changeRadio(name, value) {
      const arr = ["second", "min", "hour", "month"];
      const refName = `cron${name}`;
      let insValue;

      if (!this.$refs[refName]) return;

      if (arr.includes(name)) {
        if (value === "*") {
          insValue = 1;
        } else if (value.indexOf("-") > -1) {
          const indexArr = value.split("-");
          if(Number.isNaN(indexArr[0])){
            this.$refs[refName].cycle01 = 0
          }else {
            [this.$refs[refName].cycle01] = indexArr
          }
          [,this.$refs[refName].cycle02] = indexArr;
          insValue = 2;
        } else if (value.indexOf("/") > -1) {
          const indexArr = value.split("/");
          if(Number.isNaN(indexArr[0])){
            this.$refs[refName].average01 = 0
          }else {
            [this.$refs[refName].average01] = indexArr
          }
          [,this.$refs[refName].average02] = indexArr;
          insValue = 3;
        } else {
          insValue = 4;
          this.$refs[refName].checkboxList = value.split(",").filter(item=> item !== '');
        }
      } else if (name === "day") {
        if (value === "*") {
          insValue = 1;
        } else if (value === "?") {
          insValue = 2;
        } else if (value.indexOf("-") > -1) {
          const indexArr = value.split("-");
          if(Number.isNaN(indexArr[0])){
            this.$refs[refName].cycle01 = 0
          }else {
            [this.$refs[refName].cycle01] = indexArr
          }
          [,this.$refs[refName].cycle02] = indexArr;
          insValue = 3;
        } else if (value.indexOf("/") > -1) {
          const indexArr = value.split("/");
          if(Number.isNaN(indexArr[0])){
            this.$refs[refName].average01 = 0
          }else {
            [this.$refs[refName].average01] = indexArr
          }
          [,this.$refs[refName].average02] = indexArr;
          insValue = 4;
        } else if (value.indexOf("W") > -1) {
          const indexArr = value.split("W");
          if(Number.isNaN(indexArr[0])){
            this.$refs[refName].workday = 0
          }else {
            [this.$refs[refName].workday] = indexArr
          }
          insValue = 5;
        } else if (value === "L") {
          insValue = 6;
        } else {
          this.$refs[refName].checkboxList = value.split(",").filter(item=> item !== '');
          insValue = 7;
        }
      } else if (name === "week") {
        if (value === "*") {
          insValue = 1;
        } else if (value === "?") {
          insValue = 2;
        } else if (value.indexOf("-") > -1) {
          const indexArr = value.split("-");
          if(Number.isNaN(indexArr[0])){
            this.$refs[refName].cycle01 = 0
          }else {
            [this.$refs[refName].cycle01] = indexArr
          }
          [,this.$refs[refName].cycle02] = indexArr;
          insValue = 3;
        } else if (value.indexOf("#") > -1) {
          const indexArr = value.split("#");
          if(Number.isNaN(indexArr[0])){
            this.$refs[refName].average01 = 1
          }else {
            [this.$refs[refName].average01] = indexArr
          }
          [,this.$refs[refName].average02] = indexArr;
          insValue = 4;
        } else if (value.indexOf("L") > -1) {
          const indexArr = value.split("L");
          if(Number.isNaN(indexArr[0])){
            this.$refs[refName].weekday = 1
          }else {
            [this.$refs[refName].weekday] = indexArr
          }
          insValue = 5;
        } else {
          this.$refs[refName].checkboxList = value.split(",").filter(item=> item !== '');
          insValue = 6;
        }
      } else if (name === "year") {
        if (value === "") {
          insValue = 1;
        } else if (value === "*") {
          insValue = 2;
        } else if (value.indexOf("-") > -1) {
          insValue = 3;
        } else if (value.indexOf("/") > -1) {
          insValue = 4;
        } else {
          this.$refs[refName].checkboxList = value.split(",").filter(item=> item !== '');
          insValue = 5;
        }
      }
      this.$refs[refName].radioValue = insValue;
    },
    // 表单选项的子组件校验数字格式（通过-props传递）
    checkNumber(value, minLimit, maxLimit) {
      // 检查必须为整数
      value = Math.floor(value);
      if (value < minLimit) {
        value = minLimit;
      } else if (value > maxLimit) {
        value = maxLimit;
      }
      return value;
    },
    // 隐藏弹窗
    // hidePopup() {
    //   this.$emit("hide");
    // },
    // 填充表达式
    submitFill() {
      this.$emit("fill", this.crontabValueString);
      this.closeDialog();
    },
    clearCron() {
      // 还原选择项
      this.crontabValueObj = {
        second: "*",
        min: "*",
        hour: "*",
        day: "*",
        month: "*",
        week: "?",
        year: "",
      };
      Object.keys(this.crontabValueObj).forEach(j=>{
        this.changeRadio(j, this.crontabValueObj[j]);
      })
    },
    onSubmit() {
      console.log("111")
    },
    closeDialog() {
      this.$emit("update:visible", false);
    },
  },
};
</script>
<style scoped lang="less">
/deep/ .t-tabs__nav-scroll{
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  border-top: 1px solid #ccc;
}
.t-tab-panel{
  border: 1px solid #ccc;
  padding: 10px;
}
.pop_btn {
  text-align: center;
  margin-top: 20px;
}
.popup-main {
  position: relative;
  margin: 10px auto;
  background: #fff;
  border-radius: 5px;
  font-size: 12px;
  overflow: hidden;
}
.popup-title {
  overflow: hidden;
  line-height: 34px;
  padding-top: 6px;
  background: #f2f2f2;
}
.popup-result {
  box-sizing: border-box;
  line-height: 24px;
  margin: 25px auto;
  padding: 15px 10px 10px;
  border: 1px solid #ccc;
  position: relative;
}
.popup-result .title {
  position: absolute;
  top: -28px;
  left: 50%;
  width: 140px;
  font-size: 14px;
  margin-left: -70px;
  text-align: center;
  line-height: 30px;
  background: #fff;
}
.popup-result table {
  text-align: center;
  width: 100%;
  margin: 0 auto;
}
.popup-result table span {
  display: block;
  width: 100%;
  font-family: arial;
  line-height: 30px;
  height: 30px;
  white-space: nowrap;
  overflow: hidden;
  border: 1px solid #e8e8e8;
}
.popup-result-scroll {
  font-size: 12px;
  line-height: 24px;
  height: 10em;
  overflow-y: auto;
}
</style>
